﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Common;
using CNCSoft.ErpApps.TMS.myclass;
using CNCSoft.EData;

namespace CNCSoft.ErpApps.TMS.longGiaoVu
{
    public partial class frmEditKhoaHoc : Form
    {
        private string _makhoahoc;
        private SqlConnection conn;
        private DataSet ds;
        private CommonClass mine;
        private Calculate cal;

        private bool signTKB = false;
        private bool signGioHoc = false;

        public string Makhoahoc
        {
            get { return _makhoahoc; }
            set { _makhoahoc = value; }
        }

        public frmEditKhoaHoc()
        {
            InitializeComponent();
        }

        public frmEditKhoaHoc(string makhoahoc)
        {
            InitializeComponent();
            this.Makhoahoc = makhoahoc;
        }

        private void frmEditStartDate_Load(object sender, EventArgs e)
        {
            try
            {
                conn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);
                ds = new DataSet();
                mine = new CommonClass();
                cal = new Calculate();

                LoadGioHoc();
                LoadThoiKhoaBieu();
                LoadData(Makhoahoc);

                LoadGauge();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtSoGioHoc_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtSoGioHoc.Text != "")
                    txtSoNgayHoc.Text = (Convert.ToInt32(txtSoGioHoc.Text) / 2).ToString();
                else
                    txtSoNgayHoc.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                TinhNgayKetThuc();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            try
            {
                UpdateKhoaHoc(_makhoahoc);
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnLamLai_Click(object sender, EventArgs e)
        {
            //Cap nhat hoac thoat (nut nay chi don gian la thoat)
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();

            /*
            try
            {
                LoadGioHoc();
                LoadThoiKhoaBieu();
                LoadData(_makhoahoc);
                dateEditEndDate.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            */
        }

        #region coding
        private void LoadData(string makhoahoc)
        {
            try
            {
                LoadBangCapByMaKhoaHoc(makhoahoc);
                string sql =
                    @"SELECT
                    dmkh.TenKhoaHoc, dmkh.SoGioHoc, dmkh.SoNgayHoc,
                    dmkh.NgayBatDau, dmkh.MaNgayTrongTuan, dmkh.MaTimeSlot,
                    dmkh.DoanhThu, dmkh.ChiSo, dmkh.NgayKetThuc, dmkh.MaBangCap
                    FROM
                    DM_KHOAHOC dmkh INNER JOIN DM_NGAYTRONGTUAN dmtkb ON dmkh.MaNgayTrongTuan = dmtkb.MaNgayTrongTuan
                    INNER JOIN DM_GIOHOC dmgh ON dmgh.MaGiohoc = dmkh.MaTimeSlot
                    WHERE dmkh.MaKhoaHoc = '" + makhoahoc + "'";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                da.Fill(ds, "TableDetail");
                DataTable dt = ds.Tables["TableDetail"];
                txtTenLop.Text = dt.Rows[0][0].ToString();
                txtSoGioHoc.Text = dt.Rows[0][1].ToString();
                txtSoNgayHoc.Text = dt.Rows[0][2].ToString();
                dateEditStartDate.EditValue = dt.Rows[0]["NgayBatDau"];
                dateEditEndDate.EditValue = dt.Rows[0]["NgayKetThuc"];
                cboThoiKhoaBieu.SelectedValue = dt.Rows[0][4].ToString();
                cboGioHoc.SelectedValue = dt.Rows[0][5].ToString();
                txtDoanhThu.Text = dt.Rows[0][6].ToString();
                txtSiSo.Text = dt.Rows[0][7].ToString();
                dt.Rows.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadThoiKhoaBieu()
        {
            try
            {
                if (signTKB)
                    ds.Tables["TableTKB"].Rows.Clear();
                string sql =
                    @"SELECT MaNgayTrongTuan, TenNgayTrongTuan FROM DM_NGAYTRONGTUAN";
                mine.ExecuteDataAdapter(sql, conn, ds, "TableTKB", "MaNgayTrongTuan", "TenNgayTrongTuan", cboThoiKhoaBieu);
                signTKB = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadGioHoc()
        {
            try
            {
                if (signGioHoc)
                    ds.Tables["TableGioHoc"].Rows.Clear();
                string sql =
                    @"SELECT MaGioHoc, TenGioHoc FROM DM_GIOHOC";
                mine.ExecuteDataAdapter(sql, conn, ds, "TableGioHoc", "MaGioHoc", "TenGioHoc", cboGioHoc);
                signGioHoc = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadBangCapByMaKhoaHoc(string maKhoaHoc)
        {
            try
            {
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(@"SELECT MaBangCap from DM_KHOAHOC where MaKhoaHoc = '" + maKhoaHoc + "'", GlobalVariable.WSInfo.ConnectionString);
                da.Fill(dt);
                string maBangCap = dt.Rows[0][0].ToString();
                if (cboCapDo.Items.Count > 0)
                    cboCapDo.Items.Clear();
                DataTable dt2 = new DataTable();
                SqlDataAdapter da2 = new SqlDataAdapter(@"select MaBangCap, TenBangCap from DM_BANGCAP where MaDonVi = '" +
                    GlobalVariable.WSInfo.CompanyID + "'", GlobalVariable.WSInfo.ConnectionString);
                da2.Fill(dt2);
                this.cboCapDo.DataSource = dt2;
                this.cboCapDo.DisplayMember = "TenBangCap";
                this.cboCapDo.ValueMember = "MaBangCap";
                this.cboCapDo.SelectedValue = maBangCap;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void TinhNgayKetThuc()
        {
            try
            {
                int thu_ngaybatdau = 0;
                DateTime startdate = Convert.ToDateTime(String.Format("{0:MM/dd/yyyy}", dateEditStartDate.EditValue));
                int sogiohoc = Convert.ToInt32(txtSoGioHoc.Text);
                string mangaytrongtuan = cboThoiKhoaBieu.SelectedValue.ToString();

                string sql = @"usp_CalEndDateWithRestDate @ngaybatdau = '" + startdate + @"', 
                                @sogiohoc = " + sogiohoc + @", @mangaytrongtuan = '" + mangaytrongtuan + @"'";
                DateTime ngayketthuc = Convert.ToDateTime(SQLHelper.ExecuteScalar(conn, sql));
                dateEditEndDate.EditValue = ngayketthuc;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Bạn chưa nhập đầy đủ để tính thời gian kết thúc, xin mời bạn bổ sung !!!");
            }
        }

        private void UpdateKhoaHoc(string makhoahoc)
        {
            try
            {
                int i = 0;
                string tenkhoahoc = txtTenLop.Text;
                string sogiohoc = txtSoGioHoc.Text;
                string songayhoc = txtSoNgayHoc.Text;
                DateTime ngaybatdau = Convert.ToDateTime(String.Format("{0:MM/dd/yyyy}", dateEditStartDate.EditValue));
                DateTime ngayketthuc = Convert.ToDateTime(String.Format("{0:MM/dd/yyyy}", dateEditEndDate.EditValue));
                string mangaytrongtuan = cboThoiKhoaBieu.SelectedValue.ToString();
                string magiohoc = cboGioHoc.SelectedValue.ToString();
                double doanhthu = Convert.ToDouble(txtDoanhThu.Text);
                int siso = Convert.ToInt32(txtSiSo.Text);

                string sql =
                    @"UPDATE DM_KHOAHOC
                    SET MaKhoaHoc = @tenkhoahoc, TenKhoaHoc = @tenkhoahoc, SoGioHoc = @sogiohoc, SoNgayHoc = @songayhoc, 
                    NgayBatDau = @ngaybatdau, NgayKetThuc = @ngayketthuc, MaNgayTrongTuan = @mangaytrongtuan, MaTimeSlot = @magiohoc,
                    DoanhThu = @doanhthu, ChiSo = @siso, MaBangCap = @mabangcap
                    WHERE MaKhoaHoc = @makhoahoc";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@tenkhoahoc", tenkhoahoc);
                cmd.Parameters.AddWithValue("@sogiohoc", sogiohoc);
                cmd.Parameters.AddWithValue("@songayhoc", songayhoc);
                cmd.Parameters.AddWithValue("@ngaybatdau", ngaybatdau);
                cmd.Parameters.AddWithValue("@ngayketthuc", ngayketthuc);
                cmd.Parameters.AddWithValue("@mangaytrongtuan", mangaytrongtuan);
                cmd.Parameters.AddWithValue("@magiohoc", magiohoc);
                cmd.Parameters.AddWithValue("@doanhthu", doanhthu);
                cmd.Parameters.AddWithValue("@siso", siso);
                cmd.Parameters.AddWithValue("@makhoahoc", makhoahoc);
                cmd.Parameters.AddWithValue("@mabangcap", cboCapDo.SelectedValue.ToString());

                try
                {
                    if(conn.State != ConnectionState.Open)
                        conn.Open();
                    i = cmd.ExecuteNonQuery();
                }
                finally
                {
                    if (conn != null)
                        conn.Close();
                }

                //if (i > 0)
                    //MessageBox.Show("Thay đổi thành công");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool Validation()
        {
            try
            {
                if (txtTenLop.Text == "" || txtSoGioHoc.Text == "" || txtSoNgayHoc.Text == ""
                    || dateEditStartDate.Text == "" || dateEditEndDate.Text == ""
                    || cboThoiKhoaBieu.SelectedText == "" || cboGioHoc.SelectedText == ""
                    || txtDoanhThu.Text == "" || txtSiSo.Text == "")
                    return false;
                else
                    return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        //--------------------------

        private void LoadGauge()
        {
            try
            {
                int songayhoc = Convert.ToInt32(txtSoNgayHoc.Text.Trim());
                int songaydahoc = SoNgayDaHoc(_makhoahoc);
                linearScaleComponent1.MaxValue = songayhoc;
                linearScaleComponent1.MinValue = 0;
                linearScaleComponent1.Value = songaydahoc;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private int SoNgayDaHoc(string makhoahoc)
        {
            try
            {
                string sql = @"select count(distinct NgayHoc) as 'SoNgayDaHoc'
                                from Invoice_KhoaHoc_QTHT qtht inner join Invoice inv on inv.InvoiceNumber = qtht.InvoiceNumber
                                where inv.MaLop = '"+makhoahoc+@"'";
                int i = Convert.ToInt32(SQLHelper.ExecuteScalar(conn, sql));
                return i;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return 0;
            }
        }
        #endregion
    }
}
